<template>
  <div class="book-cart-container">
    <el-card class="cart-card">
      <template #header>
        <div class="cart-header">
          <h3>我的购物车</h3>
        </div>
      </template>

      <el-table
          :data="cartItems"
          stripe
          border
          class="cart-table"
          style="width: 100%">
        <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
        <el-table-column prop="name" label="书名" min-width="180"></el-table-column>
        <el-table-column label="图片" width="120" align="center">
          <template #default="scope">
            <img :src="$urlImage+scope.row.image" alt="书籍封面" class="book-image">
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价(￥)" width="100" align="center">
          <template #default="scope">
            {{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="数量" width="160" align="center">
          <template #default="scope">
            <el-input-number
                v-model.number="scope.row.quantity"
                :min="1"
                :max="99"
                size="small"
                @change="updateItemAmount(scope.$index, scope.row)"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="sum" label="金额(￥)" width="100" align="center">
          <template #default="scope">
            {{ scope.row.sum.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="scope">
            <el-button
                type="danger"
                size="small"
                @click="removeItem(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="cart-footer">
        <div class="left-section">
          <el-button
              type="text"
              @click="clearCart"
              class="clear-cart-btn">
            <i class="el-icon-delete"></i> 清空购物车
          </el-button>
        </div>

        <div class="right-section">
          <div class="summary-info">
            共有 <span class="highlight">{{ totalQuantity }}</span> 本书，
            合计 <span class="highlight">￥{{ totalAmount.toFixed(2) }}</span>
          </div>
          <el-button
              type="primary"
              size="medium"
              class="checkout-btn"
              @click="checkout">
            结算
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";
import { userStore } from '@/store/index.js'
import router from "@/router/index.js";
const userItemStore = userStore();

// 购物车数据
const cartItems = ref([])


//购物车信息初始化；
const initData=()=>{
  axios.post(`/cart/getCartList/${userItemStore.user.id}`).then((resp)=>{
    cartItems.value =Object.values(resp.data.items);
    totalQuantity.value = resp.data.amount;
    totalAmount.value = resp.data.totalPrice;
  })
}


// 计算属性：总数量
const totalQuantity = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

// 计算属性：总金额
const totalAmount = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.sum, 0)
})

// 更新商品金额，之后加入购物车
const updateItemAmount = (index, item) => {
  cartItems.value[index].sum = item.price * item.quantity
  updateCart(item.bookId,item.quantity);
}

//添加购物车后，更新购物车信息；
const updateCart = (bookId,quantity) => {
  axios.post(`/cart/updateCart/${bookId}/${quantity}/${userItemStore.user.id}`).then(resp=>{
    // ElMessage.success(resp.data);
    console.log(resp.data);
  })
}

// 删除商品
const removeItem = (index,item) => {
  ElMessageBox.confirm(
      `您确定要删除吗？`,
      'warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    cartItems.value.splice(index, 1)
    // 更新序号
    updateIndex();
    axios.delete(`/cart/deleteCartItem/${item.bookId}/${userItemStore.user.id}`).then(resp=>{
      ElMessage.success(resp.data);
    })
  }).catch(() => {
    ElMessage.info('已取消操作')
  })

}

// 清空购物车
const clearCart = () => {
  ElMessageBox.confirm(
      `您确定要清空购物车吗？`,
      'warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    cartItems.value = [];
    axios.delete(`/cart/clearCart/${userItemStore.user.id}`).then(resp=>{
      ElMessage.success(resp.data);
    })
  }).catch(() => {
    ElMessage.info('已取消操作')
  })


}

// 结算
const checkout = () => {
  //如何处理？？？
  router.push("/settlement").catch(error => error);
}

// 更新序号
const updateIndex = () => {
  cartItems.value.forEach((item, index) => {
    item.index = index + 1
  })
}

// 组件挂载后执行
onMounted(() => {
  // 可以在这里添加初始化逻辑，比如从本地存储加载购物车数据
  initData();
})
</script>

<style scoped>
.book-cart-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.cart-card {
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #333;
  font-weight: bold;
  font-size: 18px;
}

.cart-table {
  margin-top: 20px;
}

.book-image {
  width: 80px;
  height: 112px;
  object-fit: cover;
  border-radius: 4px;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 15px 0;
  border-top: 1px solid #ebedf0;
}

.left-section {
  flex: 1;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.summary-info {
  font-size: 16px;
  color: #333;
}

.highlight {
  color: #ff7d00;
  font-weight: bold;
}

.clear-cart-btn {
  color: #909399;
}

.clear-cart-btn:hover {
  color: #ff7d00;
}

.checkout-btn {
  background-color: #ff7d00;
  border-color: #ff7d00;
  padding: 8px 30px;
  font-size: 16px;
  border-radius: 4px;
}

.checkout-btn:hover {
  background-color: #ff9126;
  border-color: #ff9126;
}
</style>